package com.utils.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Desc：线程池的使用示例
 * @Title：TestThreadPool
 * @author: zhaoyangyang
 * @version: 1.0 
 * @date: 2017年4月20日 下午9:05:02
 */
public class ThreadPoolTest {
	public static ThreadPoolTest threadPool;
	public static ExecutorService taskPool;
	public static BlockingQueue<Runnable> queue;

	final static int baseThreadSize = 5;	//基本线程数
	final static int maxThreadSize = 10;	//最大线程数
	final static int linkedSize = 100;		//任务队列

	/*
	 * 有参的构造方法
	 */
	private ThreadPoolTest(int baseThreadSize, int maxThreadSize, int linkedSize) {
		queue = new LinkedBlockingQueue<Runnable>(linkedSize);
		taskPool = new ThreadPoolExecutor(baseThreadSize, maxThreadSize, 0L, TimeUnit.MILLISECONDS, queue);
	}
	/*
	 *无参的构造方法 
	 */
	private ThreadPoolTest() {
		queue = new LinkedBlockingQueue<Runnable>(linkedSize);
		taskPool = new ThreadPoolExecutor(baseThreadSize, maxThreadSize, 0L, TimeUnit.MILLISECONDS, queue);

	}
	/*
	 * 线程池初始化
	 */
	public static ThreadPoolTest init(int baseThreadSize, int maxThreadSize, int linkedSize) {
		if (threadPool == null) {
			threadPool = new ThreadPoolTest(baseThreadSize, maxThreadSize, linkedSize);
		}
		return threadPool;
	}

	/*
	 * 线程同步
	 */
	public static ThreadPoolTest getInstance() {
		synchronized (ThreadPoolTest.class) {
			if (threadPool == null)
				threadPool = new ThreadPoolTest();
		}
		return threadPool;
	}

	/*
	 * 添加到线程池
	 */
	public static void addThread(Runnable task) {
		taskPool.execute(task);
	}

	/*
	 * 关闭线程
	 */
	public static void closePool() {
		if (!taskPool.isShutdown()) {
			taskPool.shutdown();
		}
	}

}
